from flask import (
    Blueprint, render_template, request, flash, 
    redirect, url_for, request, jsonify, session
)
from .forms import LoginForm, RegisterForm
from flask_mail import Mail, Message
from exts import mail, db
from models import EmailCaptchaModel, UserModel
from .utils import generate_captcha
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash



bp = Blueprint(name='user', import_name=__name__, url_prefix='/user')

@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        form = LoginForm(formdata=request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if user and check_password_hash(user.password, password):
                session['user_id'] = user.id
                return redirect('/')
            else:
                flash('邮箱和密码不匹配!')
                return redirect(url_for('user.login'))
        else:
            flask('邮箱或密码格式不正确')
            return redirect(url_for('user.login'))
    else:
        return render_template('login.html')


@bp.route('/logout')
def logout():
    # 清除session 所有数据
    session.clear()
    return redirect(url_for('user.login'))


# 采用邮件注册, Flask-Mail
@bp.route('/register', methods=['POST', 'GET'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST':
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = generate_password_hash(form.password.data)
            user_model = UserModel(
                email=email,
                username=username,
                password=password,
                join_time=datetime.now()
            )
            db.session.add(user_model)
            db.session.commit()
            flash('注册成功!')
            return redirect(url_for('user.login'))
        else:
            flash('注册失败,请检查!')
            return redirect(url_for('user.register'))
    else:
        return render_template('register.html', form=form)


@bp.route('/get_captcha', methods=['POST'])
def get_captcha():
    email = request.form.get('email')
    if email:
        captcha = generate_captcha()
        message = Message(
            subject='测试邮件',
            recipients=[email],
            body=f"This is Flask test mail, 您的验证码:{captcha}"
        )
        
        mail.send(message)
        captcha_model = EmailCaptchaModel.query.filter_by(email=email).first()
        if captcha_model:
            captcha_model.captcha = captcha
            captcha_model.create_time = datetime.now()
            db.session.commit()
        else:
            captcha_model = EmailCaptchaModel(
                captcha=captcha,
                email=email
            )
            db.session.add(captcha_model)
            print(f'[Captcha]:{captcha}')
            db.session.commit()
        return jsonify({'code': 200})
    else:
        return jsonify(
            {
                'code': 200, 
                'message': 'Failed, No email address provided!'
            }
        )


@bp.route('/about_info/<int:user_id>')
def about_info(user_id):
    user = UserModel.query.get(user_id)
    return render_template('about_user.html', user=user)